<template>
  <div class="courseQuestion">
    <div class="openReplyBtn" :class="{ activeReplyBtn: activeOpenReplyBtn }">
      <el-button
        type="primary"
        class="controlBtn"
        @click="activeOpenReplyBtn = !activeOpenReplyBtn"
        >我要提问</el-button
      >
      <transition name="el-fade-in">
        <div style="flex: 1" v-show="activeOpenReplyBtn">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
            <el-form-item prop="title">
              <el-input
                v-model="ruleForm.title"
                placeholder="请输入标题"
              ></el-input>
            </el-form-item>
          </el-form>

          <editContent
            :show="activeOpenReplyBtn"
            :editId="new Date().getTime()"
            :placeholder="'输入问题详情~'"
            :menus="['image', 'link']"
            :value="qAnswerContent"
            :disabled="!userInfo.userID"
            @confirm="handleCheckTitle"
            @uploadImage="uploadImage"
          />
        </div>
      </transition>
    </div>
    <userReply
      v-for="(item, index) in replyListData"
      :key="index"
      :replyData="item"
      @handleReply="handleReply"
      @closeEdit="handleCloseEdit"
      :replyUser="replyUser"
      :currQid="currQid"
      :qid="item.qid"
      :currNo="courseInfo.currNo"
      @removeQuestion="removeQuestion"
      @uploadImage="uploadImage"
    >
      <div class="replyChildrenList" v-if="item.replyJson.length">
        <userReply
          v-for="(citem, cindex) in item.replyJson"
          :parentItem="item"
          class="replyChildren"
          :replyData="citem"
          :isChilderen="true"
          :qid="item.qid"
          :key="cindex"
          @handleReply="handleReply"
          @uploadImage="uploadImage"
        >
        </userReply>
      </div>
    </userReply>
  </div>
</template>

<script>
import UserReply from "./component/userReply.vue";
const userReply = () => import("./component/userReply.vue");
const editContent = () => import("./component/editContent.vue");
import { createReplyData } from "./component/reply";
import { createQuestion } from "@/request/qAnswer";
import { mapState } from "vuex";
import { Session } from "@/util/storage/session"
import { UploadPart } from "@/util/uploadPart.js"

export default {
  components: {
    userReply,
    editContent,
  },
  data() {
    return {
      replyListData: [
        // {
        //   qid: 2,
        //   userID: 11,
        //   iconPath: "http://test.codelover.club/icons/course/icon4.svg",
        //   classID: 3,
        //   className: "21软件技术3班",
        //   classNo: 0,
        //   degree: "大专生",
        //   eduYear: "3年",
        //   email: "1072766045@qq.com",
        //   enrollYear: 2021,
        //   facultyID: 1,
        //   majorID: 1,
        //   nickName: "",
        //   regName: null,
        //   roleFlag: 98,
        //   schoolWorkplaceID: 1,
        //   stuNum: "11111111",
        //   currNo: 64,
        //   taskID: 1,
        //   state: "正常",
        //   title: "标题~",
        //   questionBody:
        //     "因为她是大基数啊，bmi30，我之前bmi28.7的时候，一个月瘦了15斤，就晚上不吃饭",
        //   createdTime: 1660655327073,
        //   replyJson: [
        //     {
        //       userID: 12,
        //       iconPath: "https://codelover.club/icons/user/icon9.png",
        //       classID: 3,
        //       className: "21软件技术3班",
        //       classNo: 0,
        //       degree: "大专生",
        //       eduYear: "3年",
        //       email: "123@qq.com",
        //       enrollYear: 2021,
        //       facultyID: 1,
        //       majorID: 1,
        //       nickName: "",
        //       regName: null,
        //       roleFlag: 98,
        //       schoolWorkplaceID: 1,
        //       stuNum: "11111111",
        //       currNo: 64,
        //       taskID: 1,
        //       state: "正常",
        //       title: "标题~",
        //       questionBody:
        //         '回复 <a class="jump-link user" data-user-id="396378378" data-reply-id="125448736544">@bili_396378378</a> :他工作室一个员工，之前有拍一个视频是和超哥180斤的交换饮食一周，然后改变了叔贵对饮食的看法:他工作室一个员工，之前有拍一个视频是和超哥180斤的交换饮食一周，然后改变了叔贵对饮食的看法:他工作室一个员工，之前有拍一个视频是和超哥180斤的交换饮食一周，然后改变了叔贵对饮食的看法',
        //     },
        //     {
        //       userID: 13,
        //       iconPath: "https://codelover.club/icons/user/icon9.png",
        //       classID: 3,
        //       className: "21软件技术3班",
        //       classNo: 0,
        //       degree: "大专生",
        //       eduYear: "3年",
        //       email: "456@qq.com",
        //       enrollYear: 2021,
        //       facultyID: 1,
        //       majorID: 1,
        //       nickName: "",
        //       regName: null,
        //       roleFlag: 98,
        //       schoolWorkplaceID: 1,
        //       stuNum: "11111111",
        //       currNo: 64,
        //       taskID: 1,
        //       state: "正常",
        //       title: "标题~",
        //       questionBody: "发表的富文本",
        //     },
        //   ],
        // },
        // {
        //   qid: 3,
        //   userID: 14,
        //   iconPath: "https://codelover.club/icons/user/icon9.png",
        //   classID: 3,
        //   className: "21软件技术3班",
        //   classNo: 0,
        //   degree: "大专生",
        //   eduYear: "3年",
        //   email: "789@qq.com",
        //   enrollYear: 2021,
        //   facultyID: 1,
        //   majorID: 1,
        //   nickName: "",
        //   regName: null,
        //   roleFlag: 98,
        //   schoolWorkplaceID: 1,
        //   stuNum: "11111111",
        //   currNo: 64,
        //   taskID: 1,
        //   state: "正常",
        //   title: "标题~",
        //   questionBody: "发表的富文本",
        //   createdTime: 1660655327073,
        //   replyJson: [],
        // },
      ],
      replyUser: {}, // 当前选择回复的用户
      currQid: null,
      activeOpenReplyBtn: false,
      ruleForm: { title: "" },
      qAnswerContent: "",
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    baseFileUrl() {
      const { query } = this.$route;
      return `stutasks/userID_${this.studentInfo? this.studentInfo.userID : this.userInfo.userID}/currNo_${this.currNo}`; ///taskID_${this.titem.taskID}
    },
  },
  props: {
    courseInfo: Object,
    replyList: Array,
    currNo: Number,
    chooseNo: Number,
  },
  watch: {
    replyList(n) {
      this.setReplyListData(n)
    }
  },
  created() {
    let a = {
      // 课程的问答这里，我加了对应api： /api/curr_question/create, update,list,
      qid: {
        autoIncrement: true,
        // type: DataTypes.INTEGER,
        allowNull: false,
        primaryKey: true,
        comment: "课程问答，用于学习问题的交流！！",
      },
      currNo: {
        // type: DataTypes.INTEGER,
        allowNull: true,
      },
      taskID: {
        // type: DataTypes.INTEGER,
        allowNull: true,
      },
      state: {
        // type: DataTypes.ENUM("正常", "关闭", "已删除"),
        allowNull: true,
        defaultValue: "正常",
      },
      title: {
        // type: DataTypes.STRING(200),
        allowNull: false,
        comment: "问题标题",
      },
      questionBody: {
        // type: DataTypes.STRING(2000),
        allowNull: false,
        comment: "问题描述，必填，富文本",
      },
      userID: {
        // type: DataTypes.BIGINT,
        allowNull: false,
        comment: "提问者ID",
      },
      replyJson: {
        // type: DataTypes.JSON,
        allowNull: true,
        comment:
          "回答json， 格式为json数组： [{replyBody:'回答',userID:1,createdTime:12121334343,}]",
      },
    };
    if (this.replyList) this.setReplyListData(this.replyList)
  },
  methods: {
    setReplyListData(n) {
      this.replyListData = JSON.parse(JSON.stringify(n))
    },
    handleReply(qid, data) {
      // 回复框已显示时，再次点击提问者的回复则隐藏回复框
      if (this.replyUser?.userID === data.userID) {
        this.handleCloseEdit();
        return;
      }
      this.replyUser = data;
      this.currQid = qid;
    },
    handleCloseEdit() {
      this.currQid = null;
      this.replyUser = {};
    },
    handleCheckTitle(data) {
      this.qAnswerContent = data;
      this.submitForm("ruleForm");
    },
    handleCreate(data) {
      const params = createReplyData({
        currNo: this.courseInfo.currNo,
        state: "正常",
        title: this.ruleForm.title,
        questionBody: this.qAnswerContent,
        userID: this.userInfo.userID,
        replyJson: []
      });
      createQuestion(params).then((res) => {
        if (res.errno === 0) {
          Session.remove(`/api/curr_question/list?currNo=${this.$route.params.id}`)
          this.replyListData.unshift(Object.assign(res.data, this.userInfo))
          this.$antdMessage.success({ content: "发表成功!" });
          this.clearContent();
        } else {
          this.$antdMessage.error({content: res.message || "发表失败"})
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.handleCreate();
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
        this.$refs[formName].resetFields();
    },
    // 清空发表内容
    clearContent() {
      this.ruleForm.title = "";
      this.activeOpenReplyBtn = false;
      this.resetForm("ruleForm")
    },
    // 移除被删除的问题
    removeQuestion(qid) {
      this.replyListData = this.replyListData.filter(item => item.qid !== qid)
    },
    // 上传图片
    async uploadImage(item, hash, uploadImageIniserToHtml, _that, insertImgFn) {
      const taskJson = {
        chooseNo: this.chooseNo,
        currNo: this.currNo
      }
      if (!this.chooseNo || !this.currNo) return this.$antdMessage.warning('无法上传图片，刷新后重试')
      const chunkSize = 2097152
      //如果文件大于规定大小，则进行分片上传
      const res = await UploadPart.tryUploadByChunks(item, hash, this.courseInfo.currNo, false, [], this.baseFileUrl, taskJson, chunkSize);
      uploadImageIniserToHtml(res, _that, insertImgFn)
    }
  },
};
</script>

<style lang="stylus">
.courseQuestion {
  padding: 20px 0;

  .openReplyBtn {
    display: flex;
    height: 42px;

    .controlBtn {
      min-width: 100px;
      margin-right: 10px;
      height 40px
    }

    // .editReply {
    //   width: 0;
    //   height: 42px;
    //   transition: all 0.3s linear;
    //   overflow: hidden;
    // }
  }

  .activeReplyBtn {
    height: auto;

    .editReply {
      margin-top: 10px;
      width: 100%;
      height: calc(197px - 50px);

      .wangEditor {
        .w-e-text-container {
          .w-e-text {
            min-height: 95px;
            height: 95px !important;
          }
        }
      }
    }
  }
}
</style>